package bjtu.cit.bookshop.controller;

import bjtu.cit.bookshop.entities.Book;
import bjtu.cit.bookshop.service.IBookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by jia19 on 2015/10/30.
 */
@Controller
@RequestMapping("/")
public class SearchController extends BaseController {

    @Resource
    private IBookService bookService = null;

    @RequestMapping("search.do")
    public String search(HttpSession session, HttpServletRequest request, ModelMap model) {
        String loginName = checkLogin(session);
        if (loginName == null) {
            model.addAttribute("isLogin", false);
        }
        else {
            model.addAttribute("isLogin", true);
            model.addAttribute("loginName", loginName);
        }

        String keyword = request.getParameter("keyword");
        model.addAttribute("keyword", keyword);
        keyword = "%" + keyword + "%";
        Book book = new Book();
        book.setBookname(keyword);
        book.setAuthor(keyword);
        book.setCategory(keyword);
        book.setContent(keyword);
        book.setIsbn(keyword);

        String page = request.getParameter("page");

        if (page == null) {
            page = "1";
        }

        List<Book> bookList = bookService.search(book);
        model.addAttribute("bookList", getPageBookList(bookList, 10, (Integer.valueOf(page) - 1) * 10));
        int len = bookList.size();
        model.addAttribute("totalPage", len / 10 + (len % 10 == 0?0:1));
        model.addAttribute("thisPage", page);

        return "searchBook";
    }

    List<Book> getPageBookList(List<Book> bookList, int num, int offset) {
        int endIndex = offset + num;
        if (offset >= bookList.size()) {
            return null;
        }
        if (endIndex >= bookList.size()) {
            endIndex = bookList.size();
        }
        return bookList.subList(offset, endIndex);
    }

}
